package com.dd.cloud.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author zk
 */
public class ResourceDownloadUtil {
    public static void resourceDownload(HttpServletResponse response, String fileName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            //设置强制下载不打开
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            is = ResourceDownloadUtil.class.getClassLoader().getResourceAsStream(fileName);
            os = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int i;
            while ((i = is.read(bytes)) != -1) {
                os.write(bytes, 0, i);
                os.flush();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
